package com.czy.utilslib.file;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import com.czy.utilslib.debug.DebugUtil;
import com.czy.utilslib.image.ImageUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLConnection;
import java.nio.file.Files;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public class FileUtil {


    public static void deleteFile(String[] filePath){
        File file;
        file = new File(filePath[0]);
        if(file.exists()){
            boolean deleteResult = file.delete();
            DebugUtil.logR("deleteResult:" + deleteResult);
        }
        // 通过指针重置内容
        filePath[0] = "";
    }

    // 保存的路径
    public String savePath;

    /**
     * 网络数据，保存文件到当前环境路径
     * @param response      网络返回数据
     * @param context       上下文，用于提示
     * @return boolean      是否成功
     */
    public boolean saveFileByEnvironment(ResponseBody response, Context context){
        try {
            // 获取文件保存路径
            File file = new File(Environment.getExternalStorageDirectory(), "fileName");

            // 写入文件
            InputStream inputStream = response.byteStream();
            OutputStream outputStream = Files.newOutputStream(file.toPath());

            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }

            outputStream.flush();
            outputStream.close();
            inputStream.close();

            // 提示文件保存成功
            Toast.makeText(context, "文件已保存至: " + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
            return true;
        }catch (IOException e){
            Toast.makeText(context, "文件保存失败", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    /**
     * 网络数据保存到相册 String galleryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath();
     * @param response      网络返回数据
     * @param context       上下文
     * @param galleryPath   需要保存到相册的路径
     * @return              是否保存成功
     */
    public boolean saveFileToGallery(ResponseBody response, Context context, String galleryPath) {
        try {
            // 获取相册保存路径
            File file = new File(galleryPath, "fileName");

            // 写入文件
            InputStream inputStream = response.byteStream();
            OutputStream outputStream = Files.newOutputStream(file.toPath());

            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }

            outputStream.flush();
            outputStream.close();
            inputStream.close();

            // 通知系统更新相册
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            // 提示文件保存成功
            Toast.makeText(context, "文件已保存至相册: " + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
            return true;
        } catch (IOException e) {
            Toast.makeText(context, "文件保存失败", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    /**
     * 将传输的数据展示到ImageView
     * @param response Spring Boot的相应
     * @param context 上下文，用于显示Toast
     * @param imageView 需要显示的Imageview
     * @param imageUtil 用于处理的ImageUtil
     */
    public void showFileDownloadResource(ResponseBody response, Context context, ImageView imageView, ImageUtil imageUtil){
        try {
            File tempFile = File.createTempFile("prefix", ".tmp");

            try(InputStream inputStream = response.byteStream()){
                FileOutputStream output = new FileOutputStream(tempFile);

                DebugUtil.logV("Runtime","inputStream:"+inputStream);

                byte[] buffer = new byte[4096];
                int read;
                while ((read = inputStream.read(buffer)) != -1) {
                    output.write(buffer, 0, read);
                }
                output.flush();

                byte[] fileBytes = Files.readAllBytes(tempFile.toPath());

                Bitmap bitmap = imageUtil.bytesToBitmap(fileBytes);
//                Bitmap bitmap = BitmapFactory.decodeFile(tempFile.getPath());

                if(bitmap != null){
                    imageView.setImageBitmap(bitmap);
                    if (context instanceof Activity){
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(context, "图片获取成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
                else {
                    if (context instanceof Activity){
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(context, "图片获取失败：Bitmap Null", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
            catch (IOException e){
                DebugUtil.logV("Runtime","inputStream失败");
            }

            tempFile.delete();
        }
        catch (IOException e) {
            if (context instanceof Activity){
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, "图片获取失败：IOException", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }

    /**
     * 将Base64的String byte[] 数据转化为file
     * @param bytesString     Base64的String byte[]
     * @param context         上下文
     * @param imageView       显示的ImageView
     */
    public void showFileDownloadBytes(String bytesString, Context context, ImageView imageView){
        Bitmap bitmap = BitmapFactory.decodeFile(bytesString);
        if(bitmap != null){
            imageView.setImageBitmap(bitmap);
            if (context instanceof Activity){
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, "图片获取成功", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
        else {
            if (context instanceof Activity){
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, "图片获取失败：Bitmap Null", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }

    public void showByteInImageviewByFile(ResponseBody response, Context context, ImageView imageView, ImageUtil imageUtil, String fileName ){
        try{
            String filePath = createDirectory((Activity) context);

            DebugUtil.logV("Runtime","FILE_SAVE_PATH:"+filePath);
            File file = new File(filePath, fileName);
            FileOutputStream fileOutputStream = new FileOutputStream(file);

            byte[] buffer = new byte[1024];
            int bytesRead;

            InputStream inputStream = response.byteStream();

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }

            fileOutputStream.flush();
            fileOutputStream.close();
            inputStream.close();

            Bitmap bitmap = imageUtil.fileToBitmap(file);
            if(bitmap != null){
                imageView.setImageBitmap(bitmap);
                ((Activity)context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, "bitmap 不为空", Toast.LENGTH_SHORT).show();
                    }
                });
            }
            else {
                ((Activity)context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, "bitmap 为空", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }catch (IOException e){
            ((Activity)context).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    DebugUtil.logE("Runtime", "error:"+String.valueOf(e));
                    Toast.makeText(context, "IOException e", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    public Bitmap webTransferBitmap;

    private boolean isImageFile(File file) {
        String mimeType = URLConnection.guessContentTypeFromName(file.getName());
        return mimeType != null && mimeType.startsWith("image/");
    }

    /**
     * 创建文件夹
     * @param activity  获取权限的Activity
     * @return          返回路径
     */
    public String createDirectory(Activity activity){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11 及以上版本
            if (Environment.isExternalStorageManager()) {
                // 已经获得全部存储访问权限
                String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
                DebugUtil.logI("Runtime","Android 11 及以上版本");
                createDirectory(path);
                return path;
            } else {
                // 请求全部存储访问权限
                requestAllStoragePermission(activity);
                return null;
            }
        } else {
            // Android 10 及以下版本
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Test";
            DebugUtil.logI("Runtime","Android 10 及以下版本");
            createDirectory(path);
            return path;
        }
    }

    /**
     * 创建文件夹
     * @param directoryPath     传入文件夹路径
     */
    private void createDirectory(String directoryPath) {
        File downloadDir = new File(directoryPath);
        if (!downloadDir.exists()) {
            boolean r = downloadDir.mkdirs();
            DebugUtil.logV("Runtime", "文件夹"+directoryPath+"创建情况：" + r);
        }
    }

    private final int REQUEST_CODE_STORAGE_PERMISSION = 302;

    @RequiresApi(api = Build.VERSION_CODES.R)
    private void requestAllStoragePermission(Activity activity) {
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.MANAGE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.MANAGE_EXTERNAL_STORAGE}, REQUEST_CODE_STORAGE_PERMISSION);
        }
    }

    /**
     * 创建 MultipartBody.Part 上传文件类型
     * @param file              文件
     * @param fileParam         form-data参数
     * @return                  MultipartBody.Part的文件
     */
    public MultipartBody.Part createMultipartBodyPart(File file, String fileParam) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        return MultipartBody.Part.createFormData(fileParam, file.getName(), requestFile);
    }

    /**
     * 通过Uri获得文件的绝对路径
     * @param selectedVideoUri      Uri
     * @param contentResolver       Content Resolver对象
     * @return                      绝对路径
     */
    public static String getFilePathFromContentUri(Uri selectedVideoUri, ContentResolver contentResolver){
        String filePath;
        String[] filePathColumn = {MediaStore.MediaColumns.DATA};
        Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            filePath = cursor.getString(columnIndex);
            cursor.close();
        } else {
            filePath = null;
        }
        return filePath;
    }

    /**
     * 通过 照片文件（的路径）获取到Uri
     * @param context          通过上下文获取contentResolver
     * @param imageFile         文件
     * @return                  Uri
     */
    @SuppressLint("Range")
    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath},
                null
        );

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    /**
     * 将 Bitmap 数据保存到自定义文件夹中
     * @param context 应用程序上下文
     * @param bitmap 要保存的 Bitmap 数据
     * @param fileName 文件名
     * @param file_storage_path 文件存储路径
     * @return 保存文件的完整路径
     */
    public static String saveBitmapToCustomFolder(Context context, Bitmap bitmap, String fileName, String file_storage_path) {
        File storageDir = createCustomFolder(file_storage_path);
        if (storageDir != null) {
            File file = new File(storageDir, fileName);
            try {
                FileOutputStream out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                out.flush();
                out.close();
                DebugUtil.logI("Runtime", "存储成功，存储路径："+file.getPath());
                return file.getAbsolutePath();
            } catch (IOException e) {
                DebugUtil.logE("Runtime", "Error saving bitmap: " + e.getMessage());
            }
        }
        return null;
    }

    /**
     * 创建自定义文件夹
     * @param file_storage_path 文件存储路径
     * @return 创建的文件夹对象
     */
    public static File createCustomFolder(String file_storage_path) {
        File storageDir = null;

        // 检查是否有外部存储权限
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            storageDir = new File(file_storage_path);
            if (!storageDir.exists()) {
                if (!storageDir.mkdirs()) {
                    DebugUtil.logV("Runtime", "Failed to create directory");
                    storageDir = null;
                }
            }
        } else {
            DebugUtil.logV("Runtime", "External storage is not mounted.");
        }

        if(storageDir != null){
            DebugUtil.logV("Runtime", "storageDir："+storageDir.getPath());
        }

        return storageDir;
    }



}
